
/*
Copyright 2009 Peter Ekler, Akos Ludanyi, Budapest University of Technology and Economics, Department of Automation and Applied Informatics, Applied Mobile Research Group (AMORG) http://amorg.aut.bme.hu

This file is part of MobTorrent.

MobTorrent is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

MobTorrent is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with MobTorrent.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TorrentEngine;

import Logger.MTLogger;
import Settings.Preferences;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import sha1.SHA1;

/**
 *
 * @author Tyrael
 */
public class MTNetworkStatusManager
{

    public static Connection connect(String url) throws IOException
    {
        return connect(url, Connector.READ_WRITE, true);
    }


    public static Connection connect(String url, int mode) throws IOException
    {
        return connect(url, mode, true);
    }

    public static synchronized Connection connect(String url, int mode, boolean timeout) throws IOException
    {
        return Connector.open(url, mode, timeout);
    }

    public static boolean testIP(String aAddress, int aPort, MTTorrent torrent, Statistics stats)
    {
        /**
         * TODOAKOS: remove after debug
         * Do not test local IPs
         */
        if(aAddress.startsWith("192.168."))
        {
            MTLogger.writeLine("Local peer IP test is skipped. " + aAddress + ":" + aPort);
            return true;
        }

        if(aAddress.equals("127.0.0.1") && aPort == Preferences.IncommingPort)
        {
            MTLogger.write("Got back own address.");
            return false;
        }

        if(!Preferences.EnableAddressBooster)
            return true;

        boolean result = false;
        String url = Preferences.IPCheckerAddress + "?ip=" + aAddress +
            "&port=" + aPort;

        if(stats != null && torrent != null)
        {
            url += "&info_hash=" + SHA1.resultToString(torrent.getInfoHashByteArray());
            url += "&id=" + stats.getPhoneID();

        }

        try
        {
            HttpConnection hc = (HttpConnection)MTNetworkStatusManager.connect(url, Connector.READ_WRITE, true);
            MTLogger.writeLine("Connect ok to PeerChecker: " + url);
            hc.setRequestMethod(HttpConnection.GET);
            InputStream is = hc.openInputStream();
            MTLogger.writeLine("InputStream ok to PeerChecker: " + url);

            Thread.sleep(2000);

            int inputChar;
            ByteArrayOutputStream bf = new ByteArrayOutputStream();
            while((inputChar = is.read()) != -1)
            {
                bf.write(inputChar);
            }

            if(bf.toString().startsWith("ok"))
            {
                result = true;
                MTLogger.writeLine("Peer IP checked: " + url);
            }

            // close phase
            try
            {
                is.close();
                hc.close();
            }
            catch(Exception ex)
            {
                MTLogger.writeLine("PeerChecker connection close failed: " + ex.getMessage());
            }
        }
        catch(Exception ex)
        {
            MTLogger.writeLine("Connection to PeerChecker failed: " + url +
                " message: " + ex.getMessage());
        }

        return result;
    }

    public static boolean testURL(String aUrl)
    {
        if(!Preferences.EnableAddressBooster)
            return true;

        String trackerUrl = aUrl;
        String trackerPort = "80";
        if(trackerUrl.startsWith("http://"))
        {
            trackerUrl = trackerUrl.substring(7);
        }

        if(trackerUrl.indexOf(':') > 0)
        {
            trackerPort = trackerUrl.substring(trackerUrl.indexOf(':') + 1);
            if(trackerPort.indexOf('/') != -1)
            {
                trackerPort = trackerPort.substring(0, trackerPort.indexOf('/'));
            }
            trackerUrl = trackerUrl.substring(0, trackerUrl.indexOf(':'));
        }

        final int perPos = trackerUrl.indexOf('/');
        if(perPos >= 0)
        {
            trackerUrl = trackerUrl.substring(0, perPos);
        }

        try
        {
            return testIP(trackerUrl, Integer.parseInt(trackerPort), null, null);
        }
        catch(NumberFormatException e)
        {
            MTLogger.writeLine("Numberformat exception while tracker url check: " +
                e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}

